package com.example.aicloud.controller;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.aicloud.entity.User;
import com.example.aicloud.entity.dto.UserDTO;
import com.example.aicloud.service.IUserService;
import com.example.aicloud.utils.CaptchaNameUtil;
import com.example.aicloud.utils.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;


/**
 * @Description: TODO
 * @Author Mr.Tang
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IUserService userService;

    @Value("${jwt.secret}")
    private String jwtSecret;

    /**
     * 用户登录
     * @param request
     * @param userDTO
     * @return
     */
    @RequestMapping("/login")
    public Result login(HttpServletRequest request, @Validated UserDTO userDTO) {
        // 1. 非空判断
        if (!StringUtils.hasLength(userDTO.getUsername()) || !StringUtils.hasLength(userDTO.getPassword())
                || !StringUtils.hasLength(userDTO.getCaptcha())) {
            return Result.fail("用户名或密码不能为空");
        }
        // 2. 验证图片的验证码
        String redisCaptchaKey = CaptchaNameUtil.getCaptchaName(request);
        String redisCaptcha = (String) redisTemplate.opsForValue().get(redisCaptchaKey);
        if (!StringUtils.hasLength(redisCaptcha) || !redisCaptcha.equalsIgnoreCase(userDTO.getCaptcha())){
            return Result.fail("输入验证码错误");
        }
        // 3. 登录逻辑
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userDTO.getUsername());
        // 拿到数据库用户对象
        User user = userService.getOne(wrapper);
        if (user != null && passwordEncoder.matches(userDTO.getPassword(),user.getPassword())) {
            // 生成 JWT 并返回
            HashMap<String, Object> payload = new HashMap<>(){};
            payload.put("uid", user.getUid());
            payload.put("username", user.getUsername());
            // 封装 jwt 和 username 返回
            HashMap<String, String> result = new HashMap<>();
            result.put("jwt", JWTUtil.createToken(payload, jwtSecret.getBytes()));
            result.put("username", user.getUsername());
            return Result.success(result);
        }
        return Result.fail("用户名或密码错误");
    }


    /**
     * 用户注册
     */
    @RequestMapping("/register")
    public Result add(@Validated User user) {
        // 查看用户名是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        User existUser = userService.getOne(wrapper);
        if (existUser != null) {
            return Result.fail("用户名已存在");
        }

        // 将明文密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 插入数据库
        boolean result = userService.save(user);
        if (!result) {
            return Result.fail("服务错误, 添加失败");
        }
        return Result.success("添加成功!");
    }









}
